<template>
  <el-card shadow="never" class="border-0">
    <!-- 搜索 -->
    <Search :model="searchForm" @search="getData" @reset="resetSearchForm">
      <SearchItem label="搜索">
        <el-input v-model="searchForm.search" placeholder="媒体名称" clearable></el-input>
      </SearchItem>
      <template #show>
        <SearchItem label="角色名称">
          <el-select v-model="searchForm.id" placeholder="请选择角色名称" clearable>
            <el-option
              v-for="item in title_list"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </SearchItem>
      </template>
    </Search>

    <!-- 新增|刷新 -->
    <ListHeader @create="handleCreate" @refresh="getData" />

    <el-table :data="tableData" stripe v-loading="loading">
      <el-table-column
        prop="add_time"
        label="创建时间"
        :formatter="formatDate"
        width="200"
      />
      <el-table-column prop="title" label="角色名称" />
      <el-table-column prop="desc" label="角色描述" />
      <el-table-column label="激活状态" width="120">
        <template #default="{ row }">
          <el-switch
            :modelValue="row.status"
            :active-value="true"
            :inactive-value="false"
            @change="hanledStatus($event, row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button text type="primary" class="p-1" @click="openSetRule(scope.row)">
            <el-icon class="el-icon--left" :size="16">
              <Setting />
            </el-icon>
            配置权限
          </el-button>

          <el-button
            @click="handleEdit(scope.row)"
            text
            type="primary"
            class="p-1"
            v-permission="['Role,update']"
          >
            <el-icon class="el-icon--left" :size="16">
              <Edit /> </el-icon
            >修改
          </el-button>

          <el-popconfirm
            title="是否要删除该公告？"
            confirmButtonText="确认"
            cancelButtonText="取消"
            @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button
                text
                type="danger"
                class="p-1"
                v-permission="['Role,bulk_deletes']"
              >
                <el-icon class="el-icon--left" :size="16">
                  <Delete /> </el-icon
                >删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex items-center justify-center mt-5">
      <el-pagination
        background
        layout="prev, pager ,next"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="getData"
      />
    </div>
    <!-- 新增|编辑 -->
    <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
      <el-form
        :model="form"
        ref="formRef"
        :rules="rules"
        label-width="80px"
        :inline="false"
      >
        <el-form-item label="角色名称" prop="title">
          <el-input v-model="form.title" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="form.desc" placeholder="角色描述" type="textarea" :rows="5">
          </el-input>
        </el-form-item>

        <el-form-item label="所属权限" prop="permissions">
          <el-select
            filterable
            clearable
            v-model="form.permissions"
            class="input-width"
            placeholder="选择所属权限"
          >
            <el-option
              v-for="item in permission_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div class="flex items-center justify-between">
                <span class="mr-2 p-0">{{ item.name }}</span>
                <span class="p-0 m-0" v-if="item.name">
                  <el-tag class="ml-1" size="small"> {{ item.types_name }}</el-tag>
                  <el-tag class="ml-1" size="small"> {{ item.permission_name }}</el-tag>
                  <el-tag class="ml-1" size="small"> LV. {{ item.level }}</el-tag>
                </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="order">
          <el-input-number
            v-model="form.order"
            :min="0"
            :max="1000"
            class="input-width"
          />
        </el-form-item>
        <el-form-item label="启动关闭" prop="status">
          <el-switch v-model="form.status" :active-value="true" :inactive-value="false" />
        </el-form-item>
      </el-form>
    </FormDrawer>
    <!-- 权限配置 -->
    <FormDrawer ref="setRuleFormDrawerRef" title="权限配置" @submit="handleSetRuleSubmit">
      <el-tree-v2
        ref="elTreeRef"
        node-key="id"
        :check-strictly="checkStrictly"
        :default-expanded-keys="defaultExpandedKeys"
        :data="menuPermissionList"
        :props="{ label: 'name', children: 'menu_childs' }"
        show-checkbox
        :height="treeHeight"
        @check="handleTreeCheck"
      >
        <template #default="{ node, data }">
          <div class="flex items-center">
            <span class="prefix" :class="{ 'is-leaf': !data.is_menu }">
              {{ data.is_menu ? "菜单" : "规则" }}
            </span>
            <span class="ml-2 mr-2 text-sm">{{ data.name }}</span>
            <el-tag v-if="!data.is_menu" :type="tag_color[data.method]" effect="plain">{{
              data.method_name
            }}</el-tag>
          </div>
        </template>
      </el-tree-v2>
    </FormDrawer>
  </el-card>
</template>
<script setup>
import { ref, reactive, computed } from "vue";
import ListHeader from "~/components/ListHeader.vue";
import FormDrawer from "~/components/FormDrawer.vue";
import Search from "~/components/SearchForm.vue";
import SearchItem from "~/components/SearchItem.vue";
import { useInitTable, useInitForm } from "~/composables/useCommon";

import {
  getRoleList,
  postRole,
  putRole,
  deleteRole,
  patchRoleStatus,
  patchRoleMenus,
} from "~/api/role";
import { getMenuPermissionList } from "~/api/menu.js";
import { useStore } from "vuex";
import { formatDateFun } from "~/composables/util";
import { toast } from "~/composables/util";
const store = useStore();

const title_list = ref([]);

const { formatDate } = formatDateFun();
// 角色权限
const permission_list = ref([]);
const {
  searchForm,
  resetSearchForm,
  tableData,
  loading,
  currentPage,
  total,
  pageSize,
  getData,
  handleDelete,
  hanledStatus,
} = useInitTable({
  searchForm: { search: "", title: "", desc: "" },
  getList: getRoleList,
  delete: deleteRole,
  updateStatus: patchRoleStatus,
  pageSize: store.state.pageSize.RoleList,
  onGetListSuccess: (res) => {
    tableData.value = res.results.list;
    title_list.value = res.results.list;

    permission_list.value = res.results.permission_list;

    total.value = res.count;
  },
});
const {
  formDrawerRef,
  formRef,
  form,
  rules,
  editId,
  drawerTitle,
  handleSubmit,
  resetForm,
  handleCreate,
  handleEdit,
} = useInitForm({
  getData,
  create: postRole,
  update: putRole,

  form: {
    title: "",
    desc: "",
    status: true,
    permissions: null,
    order: 50,
  },
  rules: {
    title: [
      {
        required: true,
        message: "角色名称不能为空",
        trigger: "blur",
      },
    ],
    desc: [
      {
        required: true,
        message: "角色描述不能为空",
        trigger: "blur",
      },
    ],
    permissions: [
      {
        required: true,
        message: "所属权限不能为空",
        trigger: "blur",
      },
    ],
  },
});

// 配置
const setRuleFormDrawerRef = ref(null);
const menuPermissionList = ref([]);
const treeHeight = ref(0);
const roleId = ref(0);
const defaultExpandedKeys = ref([]);
const elTreeRef = ref(null);
// 当前角色拥有的权限ID
const ruleIds = ref([]);
const checkStrictly = ref(false);
const openSetRule = (row) => {
  roleId.value = row.id;
  treeHeight.value = window.innerHeight - 180;
  checkStrictly.value = true;
  getMenuPermissionList(1).then((res) => {
    menuPermissionList.value = res.results.list;
    defaultExpandedKeys.value = res.results.list.map((o) => o.id);
    setRuleFormDrawerRef.value.open();
    // 当前角色拥有的权限ID
    ruleIds.value = row.role_menus.map((o) => o);
    setTimeout(() => {
      elTreeRef.value.setCheckedKeys(ruleIds.value);
      checkStrictly.value = false;
    }, 150);
  });
};

const handleSetRuleSubmit = () => {
  setRuleFormDrawerRef.value.showLoading();
  patchRoleMenus(roleId.value, ruleIds.value)
    .then((res) => {
      toast("配置成功");
      getData();
      setRuleFormDrawerRef.value.close();
    })
    .finally(() => {
      setRuleFormDrawerRef.value.hideLoading();
    });
};
const handleTreeCheck = (...e) => {
  const { checkedKeys, halfCheckedKeys } = e[1];
  ruleIds.value = [...checkedKeys, ...halfCheckedKeys];
};

const tag_color = {
  list: "warning",
  retrieve: "warning",
  create: "",
  update: "success",
  partial_update: "success",
  bulk_restore: "success",
  bulk_deletes: "danger",
};
</script>
<style scoped>
.prefix {
  @apply bg-sky-300 p-0 m-0.5 text-blue-400 bg-opacity-25 rounded box-content h-5 w-10 flex items-center justify-center;
}

.prefix.is-leaf {
  @apply bg-gray-100 text-gray-400;
}
</style>
